import 'package:flutter/widgets.dart';

class OverlayManager {
  /// 工厂模式
  factory OverlayManager() => _getInstance();

  /// 单例
  static OverlayManager get instance => _getInstance();
  static OverlayManager? _instance;

  /// 存储对应全局的overlay管理
  final Map<String, OverlayEntry> _overlayEntryMap = {};

  OverlayManager._internal();

  static OverlayManager _getInstance() {
    _instance ??= OverlayManager._internal();
    return _instance!;
  }

  /// 检查对应的OverlayEntry是否存在
  bool exists(String keyName) => _overlayEntryMap.containsKey(keyName);

  /// 全局插入对应的试图
  void insert(BuildContext context, String keyName, WidgetBuilder widgetBuilder) {
    assert(_overlayEntryMap.containsKey(keyName) == false);
    _overlayEntryMap[keyName] = OverlayEntry(builder: widgetBuilder);
    Overlay.of(context)!.insert(_overlayEntryMap[keyName]!);
  }

  /// 全局插入对应的试图
  void remove(String keyName) {
    if (exists(keyName)) {
      _overlayEntryMap[keyName]!.remove();
      _overlayEntryMap.remove(keyName);
    }
  }

  /// 全局插入对应的试图
  void removeAll() {
    if (_overlayEntryMap.length > 0) {
      _overlayEntryMap.forEach((key, value) => value.remove());
      _overlayEntryMap.clear();
    }
  }
}
